import { pushRecord, saveInstructRecord, saveRecordInitAssignAccount, saveRecordInitAssignContact } from "../../../service/api/api-instruct-record";
import Message from 'tdesign-miniprogram/message/index';
import Toast from 'tdesign-miniprogram/toast/index';
import { instructAttachmentPreview } from "../../../service/api/api-instruct-attachment";
var upFiles = require('../../../utils/upFiles')
// pages/cues/topic/create/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentUser: {},//当前用户
    access: {} as any,// 当前用户权限
    linkageOrganizationLogo: 'lo',//作为是否为组织id的标识
    //初始化数据
    initSaveTreeAddressList: [],//初始化保存树形 通讯录 单位列表
    initSaveTreeLinkageOrganizations: [],//初始化保存树形 协助 组织列表
    //组件控制对象
    viewDrawerAddressVisible: false,//选择通讯录单位的选择器是否打开
    viewShowConfirmVisible: false,//是否显示是否推送全局的提示框
    viewDrawerLinkageVisible: false,//选择协作媒体的选择器是否打开
    viewShowSubmitVisible: false,//是否确认提交
    //加载判断字段
    isLoadAddressList: true,//指派征集单位是否在加载中
    isLoadLinkageOrganizations: true,//协作媒体是否在加载中

    titleName: '',//标题
    type: "4",//发布范围类型

    articleContent: '',//通知选题内容
    showAddress: '',//所选择的通讯录单位
    addressIds: [],//所选择的通讯录单位id
    showLinkageOrganizations: '',//所选择的指派联络人
    treeLinkageOrganizationIds: [],//所选择的指派联络人id
    instructId: '',//指令id
    isAdd: false,//是否创建选题

    //上传附件
    imageList: [],//现有的图片列表
    upFileArr: [],//上传文件列表
    upPicturesArr: [],//上传相机拍照列表
    combinedArr: [],//所有上传文件
    maxUploadLen: 10,//最大上传量
    id: [],//上传文件的id列表
    upFilesBtn: true,//上传文件按钮是否显示
    previewData: {},//预览文件
    previewDataUrlType: 'preview',
  },
  // 点击上传选择图片或者视频
  uploadFiles: function (e: any) {
    var _this = this;
    let itemList = [];
    if (this.data.access.instructSubmitAttachmentVideo) {
      itemList.push('视频');
    }
    if (this.data.access.instructSubmitAttachmentOffice) {
      itemList.push('图片');
      itemList.push('拍摄');
    }
    if (this.data.access.instructSubmitAttachmentOffice) {
      itemList.push('文件');
    }
    // if (this.data.access.instructSubmitAttachmentOther) {
    //   itemList.push('压缩文件');
    // }
    wx.showActionSheet({
      itemList: itemList,
      success: function (res) {
        const url = '/instruct/attachment/save'
        const directory = "instruct"
        if (itemList[res.tapIndex] === '拍摄') {
          upFiles.upFiles(_this, "pictrue", url, directory)
        } else if (itemList[res.tapIndex] === '视频') {
          //['mp4', 'avi', 'mov', 'wmv']
          upFiles.upFiles(_this, "video", url, directory)
        } else if (itemList[res.tapIndex] === '图片') {
          // ['jpg', 'jpeg', 'png', 'gif']
          upFiles.upFiles(_this, 'image', url, directory)
        } else {
          //['doc', 'docx', 'pdf', 'rar', 'zip']
          upFiles.upFiles(_this, 'file', url, directory)
        }
      },
      fail: function (res) {
      }
    })
  },
  // 删除上传图片 或者视频
  onDeleteFile: function (e: { currentTarget: { dataset: { index: any; }; }; }) {
    let _this = this;
    wx.showModal({
      title: '提示',
      content: '您确认删除吗？',
      success: function (res) {
        if (res.confirm) {
          let delNum = e.currentTarget.dataset.index;
          let upFileArr = _this.data.upFileArr;
          let id = _this.data.id
          upFileArr.splice(delNum, 1)
          id.splice(delNum, 1)
          _this.setData({
            upFileArr: upFileArr,
            id: id,
          })
          let upFilesArr = upFiles.getPathArr(_this);
          if (upFilesArr.length < _this.data.maxUploadLen) {
            _this.setData({
              upFilesBtn: true,
            })
          }
        } else if (res.cancel) {
        }
        let combinedArr = _this.data.upFileArr;
        _this.setData({
          combinedArr: combinedArr
        });
      }
    })
  },
  //预览图片
  async onClickPreviewImage(e) {
    const file = e.currentTarget.dataset.file
    const index = e.currentTarget.dataset.index
    if (e.currentTarget.dataset.type === "file") {
      const response = await instructAttachmentPreview({
        id: this.data.id[index],
      });
      if (response.code === 0) {
        this.setData({
          previewData: {
            title: file.name,
            onlinePreview: true,
            content: response.data,
          }
        })
        wx.navigateTo({
          url: '/pages/web/index?url=' + encodeURIComponent(this.data.previewData.content) + '&title=' + this.data.previewData.title + '&type=' + this.data.previewDataUrlType
        })
      } else {
        wx.showToast({
          title: '暂时无法预览',
          icon: 'error'
        })
      }
    } else {
      const imageList = this.data.combinedArr.map((item: any) => {
        if (item.type === 'image') {
          return item.path
        }
      })
      this.setData({
        imageList,
        viewPreviewImageVisible: true
      })
    }
  },
  //关闭图片预览
  onClosePreviewImage(e) {
    this.setData({
      viewPreviewImageVisible: false,
    });
  },
  /**
   * 预备Tree结构数据
   * @param data
   */
  readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = [];
    if (data) {
      data.forEach((val) => {
        if (val.isFolder === 1 && val.children === undefined) {
        } else {
          if (val.isContact === 0) {
            val.id = this.data.linkageOrganizationLogo + val.id
          }
          treeData.push({
            name: val.name,
            id: val.id,
            parentId: val.parentId,
            checkbox: true,
            isChildren: val.children === undefined ? 0 : 1,
            children: this.readyTreeData(val.children as AdminOrganizationData.Organization[]),
          });
        }
      });
    }
    return treeData;
  },
  /**
  * 预备Tree结构数据
  * @param data
  */
  readyTreeData2(dataTree: [], selectIds: []): any {
    if (dataTree.length > 0) {
      let list = dataTree.map(item => {
        if (item.isChildren == 1) {
          item.children = this.readyTreeData2(item.children, selectIds);
          let noChildren = item.children.filter((item) => item.checked === 0); //过滤出未选中的
          let noLength = noChildren.length;
          if (noLength == 0) { //未选中的 == 0 ，选中状态
            let pingChildren = item.children.filter((item) => item.checked === -1); //过滤出平的，未全选中
            let pingLength = pingChildren.length;
            if (pingLength == 0) {//平的 == 0，选中状态
              item.checked = 1;
            } else {//平的 != 0, 平状态 
              item.checked = -1;
            }
          } else if (noLength == item.children.length) { //未选中的 == 孩子长度，表示 父节点 未选中
            item.checked = 0;
          } else { //未选中的 >0 && < 孩子长度，表示 父节点 平的
            item.checked = -1;
          }
          // console.log('================',item.name,'================',item.checked);
        } else {
          item.checked = selectIds.includes(item.id) ? 1 : 0
        }
        return item
      })
      return list;
    }
    return []
  },
  //选择发布范围类型
  handleChangeType(e) {
    this.setData({
      type: e.detail.value,
    });
  },
  //输入标题
  onTitleNameInput(e) {
    this.setData({
      titleName: e.detail.value
    })
  },
  //输入选题内容
  onRrticleContentInput(e) {
    this.setData({
      articleContent: e.detail.value
    })
  },

  /**
   * 加载 保存 联络人
   */
  async loadAddressTreeData() {
    try {
      const response = await saveRecordInitAssignContact();
      if (response.code === 0) {
        this.setData({
          initSaveTreeAddressList: this.readyTreeData(response.data),
          isLoadAddressList: false
        })
      }
    } catch (error) { }
  },
  /**
 * 加载 初始化 指派协作 单位
 */
  async loadInitSaveTopicTreeLinkageOrganization() {
    try {
      const response = await saveRecordInitAssignAccount();
      if (response.code === 0) {
        this.setData({
          initSaveTreeLinkageOrganizations: this.readyTreeData(response.data),
          isLoadLinkageOrganizations: false
        })

      }
    } catch (error) { }
  },
  //打开通讯录单位选择器
  showAddressCascader() {
    this.setData({
      viewDrawerAddressVisible: true
    })
  },
  //打开选择联络人选择器
  showLinkageOrganizationCascader() {
    this.setData({
      viewDrawerLinkageVisible: true
    })
  },
  /**
 * Tree View 指派通讯录 点击事件
 * @param e 
 */
  onClickDrawerAddressItem(e) {
    const { names, idList } = e.detail;
    const nameString = names.join('/').substring(0, 10);
    this.setData({
      addressIds: idList,
      showAddress: nameString
    })
  },
  /**
 * Tree View 指派 协作 单位 点击事件
 * @param e 
 */
  onClickTreeViewLinkaItem(e) {
    const { names, idList } = e.detail;
    const nameString = names.join('/').substring(0, 10);
    this.setData({
      treeLinkageOrganizationIds: idList,
      showLinkageOrganizations: nameString
    })
  },
  //选择指派单位
  assignOrganizationCascadeChange(res: { detail: any; }) {
    const { selectedOptions } = res.detail;
    const ids = selectedOptions.map((item) => item.value)
    let select = selectedOptions.map((item) => item.label).join('/')
    if (select.length > 10 && select.length !== 0) {
      select = select.slice(0, 10) + "..."
    }
    this.setData({
      addressIds: ids,
      address: select
    });
  },


  /**
  * 点击选则框的确定按钮回调函数(联络人)
  */
  selectLinkageOrganizationListener(e) {
    // //获取数据源
    var allData = e.detail;
    // //获取所有子节点的选项内容(不包括父节点)
    // let leafNodes = this.allSelectleafNode(allData);
    const selectListIds = allData.map((item) => item.id)
    const selectListNames = allData.map((item) => item.lable).join('')
    this.setData({
      treeLinkageOrganizationIds: selectListIds,
      showLinkageOrganizations: selectListNames.length !== 0 ? selectListNames.slice(0, 10) + "..." : selectListNames.slice(0, 10)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: { topicId: any; mode: any }) {
    const { globalData: { access, currentUser } } = getApp();
    this.setData({
      access,
      currentUser,
      showGrade: access.cuesTopicConfigManage,
      mode: options.mode
    })
    this.loadAddressTreeData();
    this.loadInitSaveTopicTreeLinkageOrganization();
  },
  //线索征集提交
  async handleSubmit() {
    if (this.data.addressIds.length <= 0 && this.data.treeLinkageOrganizationIds.length <= 0) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请选择通讯录单位或联络人',
      });
      return false
    }
    if (this.data.titleName === '') {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 5000,
        content: '请输入标题',
      });
      return false
    }
    if (this.data.type == "5") {
      this.setData({
        treeLinkageOrganizationIds: []
      })
    } else {
      this.setData({
        addressIds: []
      })
    }
    Toast({
      context: this,
      selector: '#t-toast',
      message: '提交中',
      direction: 'column',
      duration: 2000,
      preventScrollThrough: true,
      theme: 'loading',
    });
    getApp().preventActive(async () => {
      let linkageidList = this.data.treeLinkageOrganizationIds || ''
      let addressIds = this.data.addressIds || ''
      const assignAccounts = linkageidList.filter((item) => {
        if (item.includes(this.data.linkageOrganizationLogo)) {
        } else {
          return item
        }
      })
      const assignContacts = addressIds.filter((item) => {
        if (item.includes(this.data.linkageOrganizationLogo)) {
        } else {
          return item
        }
      })
      const response = await saveInstructRecord({
        assignContacts: assignContacts,
        assignAccounts: assignAccounts,
        assignType: this.data.type,
        content: this.data.articleContent,
        name: this.data.titleName,
        attachments: this.data.id,
      });
      if (response.code === 0) {
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 1000,
          content: '提交成功',
        });
        this.setData({
          instructId: response.data.id,
          isAdd: true
        })
        this.showDialog()
        return true;
      } else {
        wx.showToast({
          title: '创建失败',
          icon: 'error'
        })
        wx.navigateBack();
        return false;
      }
    })
  },
  //确认全局通知
  async DialogConfirm() {
    const pushResponse = await pushRecord({
      id: this.data.instructId,
    });
    if (pushResponse.code == 0) {
      wx.showToast({
        title: "推送成功"
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })// 回到上一个界面
      }, 1000)
    }
    this.closeDialog()
  },
  //取消全局通知
  DialogCancel() {
    this.closeDialog()
  },
  //显示是否全局通知提示框
  showDialog() {
    this.setData({ viewShowConfirmVisible: true });
  },
  //隐藏是否全局通知提示框
  closeDialog() {
    this.setData({ viewShowConfirmVisible: false });
    setTimeout(() => {
      wx.navigateBack({
        delta: 1
      })// 回到上一个界面
    }, 1000)
  },
  //显示是否确认提交
  showSubmitDialog() {
    this.setData({ viewShowSubmitVisible: true });
  },
  //隐藏是否确认提交
  closeSubmitDialog() {
    this.setData({ viewShowSubmitVisible: false });
  },
  /**
 * 生命周期函数--监听页面卸载
 */
  onUnload() {
    wx.setStorageSync('instruct-page', 'create')
    wx.setStorageSync('instruct-create-add', this.data.isAdd)
    wx.setStorageSync('instruct-detail-index', 0)
  },

})